package com.example.thinkpad;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by ThinkPad on 2017/3/25.
 */

public class CustomViewpager extends ViewPager {
    private View leftView;
    private View rightView;
    private Map<Integer, ImageView> childMaps = new HashMap<>();

    public CustomViewpager(Context context) {
        super(context);
    }

    public CustomViewpager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void addChildView(ImageView imageView, int position) {
        childMaps.put(position, imageView);
    }

    public void removeChildView(int position) {
        childMaps.remove(position);
    }

    /**
     * @param position  当前界面的索引
     * @param offset  当前界面滑动的比例值(滑动的宽/控件宽)[0-1]
     * @param offsetPixels  当前界面滑动的像素值
     */

    @Override
    protected void onPageScrolled(int position, float offset, int offsetPixels) {
        super.onPageScrolled(position, offset, offsetPixels);
        leftView = childMaps.get(position);
        rightView = childMaps.get(position + 1);
        startlaunchAnimation(leftView, rightView, position, offset, offsetPixels);
    }

    private void startlaunchAnimation(View leftView, View rightView, int position, float offset, int offsetPixels) {

        float MIN_SCALE = 0.5f;
        if (rightView != null) {
            rightView.setAlpha(offset);
            rightView.setTranslationX(-(rightView.getWidth() - offsetPixels));
            float scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (Math.abs(offset));
            rightView.setScaleX(scaleFactor);
            rightView.setScaleY(scaleFactor);
        }

        if (leftView != null) {
            leftView.bringToFront();
        }

    }
}
